package com.ht.common.core.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MsgUtils {

	private static Date oldTime = new Date();
	private static int msgid = 0;
	private static Logger logger = LoggerFactory.getLogger(MsgUtils.class);


	public static String createMessage(String messageId, String siglewinpath, String messageType) throws Exception {
		String fileName = "";
		String name = "";
		try {
		//	ReportHead hd = obj.getReportHead();
			String path = siglewinpath;
			String pathTemp = siglewinpath + "/temp";
			String tim = FileUtil.GetTimeToString(1);

			FileUtil.createDir(path);
			FileUtil.createDir(pathTemp);
			// 报文命名定义
			// [name]_[sender_code]_[send_time]_[业务主键].xml
			name = messageId + ".xml";
			fileName = path + "/" + name;
			pathTemp = pathTemp + "/" + name;
//			boolean b = false;
//			b = JaxbUtil.convertToXml(obj, fileName);
//			if (!b) {
//				name = "";
//			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return fileName;
	}

	/**
	 * 文件压缩，支持 单文件和文件夹，不支持多层文件夹
	 * 
	 * @param filepath 压缩前文件名包括路径
	 * @param zippath  压缩后zip文件名 包括路径
	 */
	public static void zipFileAndDeleteOldFile(String filepath, String zippath) {
		File file = null;
		try {
			file = new File(filepath);// 要被压缩的文件夹
			zipFile(file, zippath);
			
			
		} catch (FileNotFoundException e) {
			logger.error("zip压缩失败：文件未找到，" + e.getMessage(), e);
		} catch (IOException ex) {
			logger.error("zip压缩失败：写入zip文件io异常，" + ex.getMessage(), ex);
		}finally {
			if(file != null) {
				boolean deleteFlag = file.delete();
				System.out.println(deleteFlag);
			}
		}
	}
	 /**
     *   2个文件压缩
     *  @param file 被压缩的文件
     *  @param file2 被压缩的文件
     * @param zippath  压缩后zip文件名 包括路径 
     */
    public static void zipFile(File file ,File file2,String zippath) throws FileNotFoundException,IOException{
		try {
	        File zipFile = new File(zippath);
	        ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
        	InputStream input = new FileInputStream(file);	 
        	ZipEntry zip=new ZipEntry(file.getName());
        	zip.setTime(file.lastModified());
            zipOut.putNextEntry(zip);
        	
            int temp = 0;
            while((temp = input.read()) != -1){
                zipOut.write(temp);
            }
            input.close();
          
            //文件2 压缩
            if (file2!=null && file2.exists()){
	            InputStream input2 = new FileInputStream(file2);	 
	        	
	        	ZipEntry zip2=new ZipEntry(file2.getName());
	        	zip2.setTime(file2.lastModified());
	            zipOut.putNextEntry(zip2);
	        	
	            int temp2 = 0;
	            while((temp2 = input2.read()) != -1){
	                zipOut.write(temp2);
	            }
	            input2.close();
            }
	        
	        zipOut.close();
	        zipOut=null;
	        
		} catch (FileNotFoundException e) {  
        	logger.error("zip压缩失败：文件未找到，"+e.getMessage(),e);  
        	throw e;
        } catch (IOException ex) {  
        	logger.error("zip压缩失败：写入zip文件io异常，"+ex.getMessage(),ex);
        	throw ex;
        }
	} 
    
    /**
     * 单个文件压缩，不支持多层文件夹
     * @param file 被压缩的文件
     * @param zippath  压缩后zip文件名 包括路径 
     */
    public static void zipFile(File file ,String zippath) throws FileNotFoundException,IOException{
    	zipFile(file,null,zippath);
	} 
    
    /** 
     * 将字符串写入指定文件(当指定的父路径中文件夹不存在时，会最大限度去创建，以保证保存成功！) 
     * 
     * @param res            原字符串 
     * @param filePath 文件路径 
     * @return 成功标记 
     */ 
     public  static  boolean string2File(String res, String filePath) { 
             boolean flag =  true; 
            BufferedReader bufferedReader =  null; 
            BufferedWriter bufferedWriter =  null; 
             try { 
                    File distFile =  new File(filePath); 
                     if (!distFile.getParentFile().exists()) distFile.getParentFile().mkdirs(); 
                    bufferedReader =  new BufferedReader( new StringReader(res)); 
                    bufferedWriter =  new BufferedWriter( new FileWriter(distFile)); 
                     char buf[] =  new  char[1024];          //字符缓冲区 
                     int len; 
                     while ((len = bufferedReader.read(buf)) != -1) { 
                            bufferedWriter.write(buf, 0, len); 
                    } 
                    bufferedWriter.flush(); 
                    bufferedReader.close(); 
                    bufferedWriter.close(); 
            }  catch (IOException e) { 
                    e.printStackTrace(); 
                    flag =  false; 
                     return flag; 
            }  finally { 
                     if (bufferedReader !=  null) { 
                             try { 
                                    bufferedReader.close(); 
                            }  catch (IOException e) { 
                                    e.printStackTrace(); 
                            } 
                    } 
                    if (bufferedWriter !=  null) { 
                         try { 
                        	 bufferedWriter.close(); 
                        }  catch (IOException e) { 
                                e.printStackTrace(); 
                        } 
                } 
            } 
             return flag; 
    }
     
     /**
      * 删除单个文件
      *
      * @param fileName
      *            要删除的文件的文件名
      * @return 单个文件删除成功返回true，否则返回false
      */
     public static boolean deleteFile(String fileName) {
         File file = new File(fileName);
         // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
         if (file.exists() && file.isFile()) {
             if (file.delete()) {
                 System.out.println("删除单个文件" + fileName + "成功！");
                 return true;
             } else {
                 System.out.println("删除单个文件" + fileName + "失败！");
                 return false;
             }
         } else {
             System.out.println("删除单个文件失败：" + fileName + "不存在！");
             return false;
         }
     }
    
	public static String getMessageID() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmSSS");
		long times = System.currentTimeMillis();
		Date date = new Date(times);
		String strTime = sdf.format(date);

		long timeMillis = System.currentTimeMillis();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		String sp_time = sf.format(oldTime);
		String current_time = sf.format(Long.valueOf(timeMillis));
		if (!(sp_time.equals(current_time))) {
			oldTime = new Date(timeMillis);
			msgid = 0;
		}
		if (msgid <= 99999999)
			msgid += 1;

		return strTime + msgid;
	}

}
